// pages/myCollection/index.js
const api = require('../../config/api')
const request = require('../../utils/request')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sortList: [],
    selectIndex: '',
    dataList: [],
    source: 2,
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let source = 2
    if (options.source) {
      source = 1
      wx.setNavigationBarTitle({
        title: '全部训练',
      })
    }
    this.setData({
      source: source,
    })
    this.getClassify()
  },
  // 分类列表
  async getClassify() {
    const userId = wx.getStorageSync('userId')
    const res = await request.post(api.collectionClassify, {
      source: 1,
      userId: userId,
    })
    if (res.httpStatus === 200) {
      this.setData({
        selectIndex: res.data[0]?.classifyId,
        sortList: res.data.splice(0, 2),
        loading: true,
      })
      this.getCollectList()
    }
  },
  async getCollectList() {
    let { source, selectIndex } = this.data
    const userId = wx.getStorageSync('userId')
    if (!selectIndex) {
      return
    }
    const res = await request.post(api.collectTraining, {
      userId: userId,
      classifyId: selectIndex,
      source: source,
    })
    if (res.httpStatus === 200) {
      this.setData({
        dataList: res.data,
        loading: false,
      })
    }
  },
  clickItem: function (e) {
    const { id } = e.currentTarget.dataset
    this.setData({
      selectIndex: id,
      loading: true,
    })
    this.getCollectList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let { selectIndex } = this.data
    if (selectIndex) {
      this.setData({
        loading: true,
      })
      this.getCollectList()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
